<?php
namespace app\mobile\controller;
use app\api\model\MaliceIp;
use app\api\model\Client;
use app\api\model\Config;
use app\api\model\Kf;
use app\api\model\Users;
use app\api\model\WxUser;
use think\Controller;
use think\Cookie;
use think\Session;

class Common extends Controller
{
    //session作用域
    protected $session_prefix = 'api';
    //回调地址
    protected $redirect_url = null ;
    //配置项
    private static $config = null;

    public function _initialize()
    {
        //设置当前session的作用域
        Session::prefix($this->session_prefix);
        cookie(['prefix' => 'api','expire' => 1296000]);

        //自动初始化网站的配置
        $this->setConfig();

        //处理回调地址
        $this->save_redirect_url();
        $this->chkIp();
    }

    //查看当前用户ip是否被禁用
    public function chkIp()
    {
        $maliceModel = new MaliceIp();
        if(in_array(real_ip(),$maliceModel->getAllIp()))
        {
            die(json_encode(['error'=>1,"msg"=>"对不起，您当前状态不能进行对话，请联系客服热线: ".$this->config('kfphone')],JSON_UNESCAPED_UNICODE));
        }
    }

    public function  setConfig()
    {
        if(empty(self::$config))
        {
            $ConfigModel = new Config();
            self::$config = $ConfigModel->total();
        }
    }

    //获取配置
    public function config($key)
    {
        $config = self::$config;
        if(empty($config))
        {
            $this->setConfig();
        }
        return isset($config[$key]) ? $config[$key] : null;
    }

    //检查登录状态
    protected function check_login()
    {
        return !empty(session('enc_client_id'));
    }



    //redirect_url回调地址处理
    protected function save_redirect_url()
    {
        $this->redirect_url = base64_decode(input('param.redirect_url'));
    }

    //关闭一个链接
    protected function close()
    {
        $post = json_decode(base64_decode(file_get_contents('php://input')),true);
        if( !isset($post['secret']) || !isset($post['client_id']) || !isset($post['type']) || !isset($post['user_id']))
        {
            return "非法操作";
        }
        //验证秘钥正确性
        if(!$this->chkAppKey(['appkey'=>config('Chat.app_key'),'secret'=>$post['secret']]))
        {
            return "秘钥错误";
        }

        //通知所有客户端，该用户下线了
        $UserModel = new Client($this->modelDefaultParam());

        @$UserModel->sendAllClient(json_encode(['type'=>'OneClose','client_id'=>$post['user_id']]));


        return "通知完毕: ".$post['client_id'].":".$post['session'];
    }

    //当某个人上线
    protected function clientOn($client_id)
    {
        //通知所有客户端，该用户上线
        $UserModel = new Client($this->modelDefaultParam());
        @$UserModel->sendAllClient(json_encode(['type'=>'OneOnLine','client_id'=>$client_id]));
    }

    //验证一个app_key正确性 ['appkey','secret']
    protected function chkAppKey($args)
    {
        return !empty($args['appkey']) && !empty($args['secret']) && password_verify($args['appkey'],$args['secret']);
    }

    //游客自动登录
    protected function login()
    {
        $UserModel = new Users($this->modelDefaultParam());
        $user = [
            'enc_client_id' => cookie('enc_client_id'),
            'token'     => cookie('token')
        ];
        $loginMsg = $UserModel->login($user);
        $this->setCurrentUserMsg($loginMsg);

    }


    /**获取当前登录的user_id，，
     * @param bool|false $isEnc 是否加密的
     * @return int|string
     */

        protected function getCurrentUserid($isEnc = false)
        {
            return !$isEnc ? session('client_id') : session('enc_client_id');
        }

    /**加密一个客户端id
     * @param $client_id
     * @return string
     */
    protected function EncUserid($client_id)
    {
        return sha1($client_id);
    }

    /**设置当前用户信息
     * @param $args client_id,user_name,nickname
     */
        protected function setCurrentUserMsg($args)
        {
            $default = [
                'client_id'=>"",
                'user_name'=>"",
                'nickname'=>"",
                'token'   => "",
                'is_kf'    => 0
            ];
            $args = array_merge($default,$args);
            $enc_client_id = $this->EncUserid($args['client_id']);

            session('client_id',$args['client_id']);
            session('enc_client_id',$enc_client_id);
            session('user_name',$args['user_name']);
            session('nickname',$args['nickname']);
            session('isKf',$args['is_kf']);

            cookie('enc_client_id',$enc_client_id);
            cookie('token',$args['token']);
        }

    /**
     * 当token发生改变是，必须执行该操作
     */
        protected function setCurrentToken($token)
        {
            cookie('token',$token);
        }

    /**
     * 获取当前cookie的token
     */
    protected function getCurrentToken()
    {
        return cookie('token');
    }

        //判断用户是否客服
        protected function isKf($enc_client_id)
        {
            $KfModel = new Kf($this->modelDefaultParam());
            $kf = $KfModel->info(['enc_client_id'=>$enc_client_id]);
            return !empty($kf);
        }

        protected function modelDefaultParam($args = [])
        {
            $default = [
                'user_id'       => $this->getCurrentUserid(),
                'user_name'     => session('user_name'),
                'nickname'      => session('nickname'),
                'isKf'         => session('isKf')
            ];
            return array_merge($default,$args);
        }
    /**
     * 判断当前登录用户是否客服
     *
     */
    protected function CurrentUserIsKf()
    {
        return session('isKf') == 1;
    }
    //验证用户token，返回新的token，并给客户端发送token ['enc_client_id','token']
    protected function chkToken($args)
    {
        if(!isset($args['enc_client_id']) || !isset($args['token'])) return false;

        $userModel = new Users();
        $clientModel= new Client();
        //获取用户信息
        $info = $userModel->user_info(['enc_client_id'=>$args['enc_client_id']]);

        if(!$info || empty($info))
        {
            return false;
        }
        //验证token
        if(!$userModel->chkToken(array_merge(['token' => $args['token']],$info))) return false;
//        //生成新的token
//        $token =  $userModel->resetEncString(['client_id'=>$info['client_id'],'client_secrect'=>$info['client_secrect']]);
//        //设置cookie的token
//        $this->setCurrentToken($token);
//        //给用户返回新的token
//        $clientModel->sendOneUser(['type'=>'setToken','msg'=>['token'=>$token]],$args['enc_client_id']);
        return true;
    }

    public function isClientOnLine($client_id)
    {
        $clientModel = new Client();
        return $clientModel->isOnLine($client_id);
    }

}